import {RuleInfoType} from "@/api/sys/admin/rule-info/types";
import {cloneDeep, initPageQuery} from "@/utils/common-fn";
import {getRuleInfoByIdApi, getRuleInfoListApi} from "@/api/sys/admin/rule-info";
import {DictType, OpenFormType} from "@/utils/enum-type";
import {useGetOptions} from "@/utils/use/use-get-options";

export const useRuleInfoViewStore = defineStore('ruleInfoView', () => {
    /**
     * 公共
     */
    const title = '规则说明'
    // 打开表单类型
    let openFormType: Ref<OpenFormType> = ref(OpenFormType.Add)
    // 最好初始化表单类型
    const initForm: RuleInfoType = {id: -1, title: '', type: 1, status: 1, sort: 1}
    // 获取options
    let allOptions = useGetOptions(DictType.Status, DictType.RuleInfoType);
    const statusOptions = computed(() => allOptions.value[0])
    const ruleInfoTypeOptions = computed(() => allOptions.value[1])
    /**
     * table相关
     */
        // table数据
    let tableData: Ref<RuleInfoType[]> = ref([])
    // 总数
    const total = ref(0)
    // 分页信息,以及查询条件,用于发送api
    const queryData = reactive(initPageQuery<RuleInfoType>({order: {id: 'desc'}}))

    /**
     * 表单相关
     */
        // 弹出框可见
    const visible = ref(false)
    // 表单数据
    const formData: Ref<RuleInfoType> = ref(cloneDeep(initForm))

    /**
     * 方法相关
     */
    // 设置编辑对话框可见
    function setVisible(bolValue: boolean) {
        visible.value = bolValue
    }

    // 获取列表
    async function getList() {
        [tableData.value, total.value] = await getRuleInfoListApi(queryData);
        allOptions = useGetOptions(DictType.Status, DictType.RuleInfoType);
    }

    // 打开表单
    function open(): void
    async function open(id: number): Promise<void>
    async function open(id?: number) {
        if (id) {
            // 编辑
            formData.value = await getRuleInfoByIdApi(id)
            openFormType.value = OpenFormType.Edit
        } else {
            // 新增
            formData.value = cloneDeep(initForm)
            openFormType.value = OpenFormType.Add
        }
        setVisible(true)
    }

    return {
        queryData, total, tableData, title, openFormType,
        statusOptions, ruleInfoTypeOptions, visible, formData,
        getList, open, setVisible
    }
})